package com.jic.interaction.ChinaPost.sever;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jic.interaction.common.enums.RedisKey;
import com.jic.interaction.common.utils.HttpClientUtil;
import com.jic.interaction.common.utils.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;


@Component
@Slf4j
@EnableScheduling
public class NonceService {
    @Autowired
    private RedisService redisService;

    @Value("${wz.appid}")
    private String appid;

    public String getNonceTicket(String userId) {
        try {
            String accessToken = redisService.getValue(RedisKey.WZ_ACCESS_TOKEN);
            if (StringUtils.isNotEmpty(accessToken)) {
                Map<String, String> params = new HashMap<>();
                params.put("app_id", appid);
                params.put("access_token", accessToken);
                params.put("type", "NONCE");
                params.put("version", "1.0.0");
                params.put("user_id", userId);
                String body = HttpClientUtil.doRequestGet("https://svrapi.webank.com/api/oauth2/api_ticket", params, null);
                if (StringUtils.isNotEmpty(body)) {
                    JSONObject jsonObject = JSON.parseObject(body);
                    String code = jsonObject.getString("code");
                    // code不是0是表示获取失败
                    if ("0".equals(code)) {
                        JSONArray tickets = jsonObject.getJSONArray("tickets");
                        JSONObject ticket = tickets.getJSONObject(0);
                        return ticket.getString("value");
                    } else {
                        log.error(jsonObject.getString("msg"));
                    }
                } else {
                    log.error("获取NonceTicket时，响应值为空");
                }
            } else {
                log.error("获取NonceTicket时，accessToken为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
